package com.neuedu.yyzx.config.security;

import com.neuedu.yyzx.po.User;
import com.neuedu.yyzx.service.UserService;
import com.neuedu.yyzx.utils.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author 金山
 * 项目：yyzx
 * site: https://blog.fulfill.com.cn
 * 描述  系统安全工具
 * @data 2025/4/1614:41
 */
@Component
public class SecurityUtils {


    // 线程安全 每个线程独立
    private static final ThreadLocal<User> authorizationThreadLocal = new NamedThreadLocal("UserInfo");

    @Autowired
    private UserService userService;


    /**
     * 获取用户身份
     */
    public synchronized User getUserInfo() {
        User userInfo = null;
        if (authorizationThreadLocal.get() == null) {
            // 第一次设置
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            // HttpServletResponse response = attributes.getResponse();
            String token = request.getHeader("Authorization");
            Long userId = JWTUtils.getUserId(token);

            User user = userService.getById(userId);
            // 设置线程对象
            authorizationThreadLocal.set(user);
        }

        // 从线程对象中获取用户身份
        userInfo = authorizationThreadLocal.get();

        return userInfo;
    }
}
